import { app, BrowserWindow, ipcMain, screen, Tray, Menu, nativeImage } from 'electron';
import path from 'node:path';
import fs from 'node:fs';
const squirrelStartup = await import('electron-squirrel-startup').then(m => m.default || m);

import { initEvent } from '../event/index.js';
import Store from 'electron-store';
import Config from '../plugins/db/config.js';

const windowConfig = new Config();
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = "true";
const configObj = windowConfig.get();

if (squirrelStartup()) app.quit();
// 关键修改1：添加wait-on依赖后需引入
// const waitOn = require('wait-on'); 

const getImagePath = (img) => 
  process.env.NODE_ENV === 'development' ? img : path.join(process.resourcesPath, img);

Store.initRenderer();

const trackWindowState = (win) => {
  win.on('maximize', () => win.webContents.send('window-state-changed', true));
  win.on('unmaximize', () => win.webContents.send('window-state-changed', false));
};

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    x: windowConfig.config.x,
    y: windowConfig.config.y,
    width: windowConfig.config.width,
    height: windowConfig.config.height,
    minWidth: windowConfig.config.minWidth,
    minHeight: windowConfig.config.minHeight,
    frame: false,
    skipTaskbar: true,
    alwaysOnTop: windowConfig.config.isAlwaysOnTop,
    transparent: true,
    webPreferences: {
      preload: path.join(__dirname, '../preload/preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  ipcMain.on('set-is-top', (_, isTop) => {
    mainWindow.setAlwaysOnTop(isTop);
    windowConfig.set('mainWindow.isAlwaysOnTop', isTop);
  });

  if (process.env.NODE_ENV === 'development') {
    // 关键修改2：添加dev server等待逻辑
    /* await waitOn({ 
      resources: [process.env.VITE_DEV_SERVER_URL],
      timeout: 30000 
    }); */

    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
      .catch(err => {
        console.error('❌ Dev server load failed:', err);
        app.quit();
      });
    
    mainWindow.webContents.openDevTools({ mode: 'detach' });
    
    mainWindow.webContents.on('did-fail-load', () => {
      setTimeout(() => mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL), 1000);
    });
  } else {
    const indexPath = path.join(__dirname, '../renderer/index.html');
    if (!fs.existsSync(indexPath)) throw new Error('Missing production file');
    mainWindow.loadFile(indexPath).catch(err => app.quit());
  }

  // Window state handlers
  mainWindow.on('moved', () => {
    const bounds = mainWindow.getBounds();
    windowConfig.set('mainWindow.x', bounds.x);
    windowConfig.set('mainWindow.y', bounds.y);
    // ...吸附逻辑保持不变
  });

  mainWindow.on('resize', () => {
    const bounds = mainWindow.getBounds();
    windowConfig.set('mainWindow.width', bounds.width);
    windowConfig.set('mainWindow.height', bounds.height);
  });

  return mainWindow;
};

// Auto-start configuration
app.setLoginItemSettings({
  openAtLogin: configObj.autoStart,
  openAsHidden: configObj.autoStart
});

const initTray = (mainWindow) => {
  const tray = new Tray(nativeImage.createFromPath(getImagePath('static/note.png')));
  tray.setContextMenu(Menu.buildFromTemplate([{
    label: "Quit",
    click: () => app.quit()
  }]));
  tray.on('double-click', () => mainWindow.show());
};

// 关键修改3：修复变量名一致性
app.whenReady().then(() => {
  const mainWindow = createWindow(); // 统一使用mainWindow变量名
  trackWindowState(mainWindow);
  initEvent(app);
  initTray(mainWindow);
  
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});